using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApi001.Domain;
using WebApi001.inetrface.Data;

namespace WebApi001.Implement.Data
{
  public class Efrespository<T> : IRespository<T> where T : BaseEntity
  {
    public Efrespository(WebApi001DoContexe db)
    {
      _db = db;
    }
    public IQueryable<T> Table
    {
      get
      {
        return Entity;
      }
    }
    private DbSet<T> _entity;
    private DbSet<T> Entity
    {
      get
      {
        if (_entity == null)
        {
          _entity = _db.Set<T>();
        }
        return _entity;
      }
    }
    private WebApi001DoContexe _db;

    public void Add(T entity)
    {
      entity.IsActived = true;
      entity.IsDeleted = false;
      entity.CreatedTime = DateTime.Now;
      entity.UpdateTime = DateTime.Now;
      Entity.Add(entity);
      _db.SaveChanges();
    }

    public void Add(IEnumerable<T> entites)
    {
      foreach (var entity in entites)
      {
        entity.IsActived = true;
        entity.IsDeleted = false;
        entity.CreatedTime = DateTime.Now;
        entity.UpdateTime = DateTime.Now;
      }
      Entity.AddRange(entites);
      _db.SaveChanges();
    }

    public void Delete(T entites)
    {
      Entity.Remove(entites);
      _db.SaveChanges();
    }

    public void Delete(IEnumerable<T> entites)
    {
      Entity.RemoveRange(entites);
      _db.SaveChanges();
    }

    public T GetById(int id)
    {
      return Entity.Where(x => x.Id == id).FirstOrDefault();
    }

    public void Update(T entity)
    {
      Entity.Update(entity);
      _db.SaveChanges();
    }

    public void Update(IEnumerable<T> entites)
    {
      Entity.UpdateRange(entites);
      _db.SaveChanges();
    }
  }
}
